import axios from 'axios'

// 响应数据接口
interface ApiResponse<T = any> {
  code: number
  message?: string
  msg?: string
  data: T
  success?: boolean
}

// 请求配置接口
interface RequestConfig {
  showLoading?: boolean
  showError?: boolean
  headers?: Record<string, string>
  timeout?: number
  params?: Record<string, any>
}

class RequestService {
  private instance: any
  private loadingCount = 0

  constructor() {
    // 创建axios实例
    this.instance = axios.create({
      baseURL: 'https://cbam.hongyuan3e.com/prod-api',
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    })

    // 请求拦截器
    this.setupRequestInterceptor()
    
    // 响应拦截器
    this.setupResponseInterceptor()
  }

  // 设置请求拦截器
  private setupRequestInterceptor() {
    this.instance.interceptors.request.use(
      (config: any) => {
        // 显示加载状态
        if (config.showLoading !== false) {
          this.showLoading()
        }

        // 添加认证token
        const token = this.getToken()
        if (token) {
          config.headers.Authorization = `${token}`
        }

        // 添加请求时间戳
        config.headers['X-Request-Time'] = Date.now().toString()

        return config
      },
      (error: any) => {
        this.hideLoading()
        return Promise.reject(error)
      }
    )
  }

  // 设置响应拦截器
  private setupResponseInterceptor() {
    this.instance.interceptors.response.use(
      (response: any) => {
        this.hideLoading()

        const { data } = response

        // 处理业务错误 - 只有code为200才是成功
        if (data.code !== 200) {
          if (data.code == 401) {
            this.handleUnauthorized()
            return
           }
          this.handleBusinessError(data)
         
          return Promise.reject(new Error(data.msg || data.message || '请求失败'))
        }

        return data
      },
      (error: any) => {
        this.hideLoading()
        this.handleNetworkError(error)
        return Promise.reject(error)
      }
    )
  }

  // 获取token
  private getToken(): string | null {
    if (process.client) {
      return localStorage.getItem('token')
    }
    return null
  }

  // 显示加载状态
  private showLoading() {
    this.loadingCount++
    if (process.client) {
      // 这里可以集成你的loading组件
      // 例如：this.$loading.show()
    }
  }

  // 隐藏加载状态
  private hideLoading() {
    this.loadingCount--
    if (this.loadingCount <= 0) {
      this.loadingCount = 0
      if (process.client) {
        // 这里可以集成你的loading组件
        // 例如：this.$loading.hide()
      }
    }
  }

  // 处理业务错误
  private handleBusinessError(data: ApiResponse) {
    if (process.client) {
      // 使用toast显示错误信息
      const { $toast } = useNuxtApp()
      if ($toast) {
        $toast.error(data.msg || data.message || '请求失败')
      } else {
        console.error('业务错误:', data.msg || data.message)
      }
    }
  }

  // 处理网络错误
  private handleNetworkError(error: any) {
    let message = '网络错误'

    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 400:
          message = '请求参数错误'
          break
        case 401:
          message = '未授权，请重新登录'
          this.handleUnauthorized()
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求地址不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = data?.message || `请求失败 (${status})`
      }
    } else if (error.request) {
      message = '网络连接失败'
    } else {
      message = error.message || '请求配置错误'
    }

    if (process.client) {
      // 使用toast显示错误信息
      const { $toast } = useNuxtApp()
      if ($toast) {
        $toast.error(message)
      } else {
        console.error('网络错误:', message)
      }
    }
  }

  // 处理未授权错误
  private handleUnauthorized() {
    if (process.client) {
      // 清除本地存储的认证信息
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      
      // 跳转到登录页面
      window.location.href = '/login'
    }
  }

  // GET请求
  async get<T = any>(url: string, config?: RequestConfig): Promise<ApiResponse<T>> {
    return this.instance.get(url, config)
  }

  // POST请求
  async post<T = any>(url: string, data?: any, config?: RequestConfig): Promise<ApiResponse<T>> {
    return this.instance.post(url, data, config)
  }

  // PUT请求
  async put<T = any>(url: string, data?: any, config?: RequestConfig): Promise<ApiResponse<T>> {
    return this.instance.put(url, data, config)
  }

  // DELETE请求
  async delete<T = any>(url: string, config?: RequestConfig): Promise<ApiResponse<T>> {
    return this.instance.delete(url, config)
  }

  // PATCH请求
  async patch<T = any>(url: string, data?: any, config?: RequestConfig): Promise<ApiResponse<T>> {
    return this.instance.patch(url, data, config)
  }

  // 上传文件
  async upload<T = any>(url: string, file: File, config?: RequestConfig): Promise<ApiResponse<T>> {
    const formData = new FormData()
    formData.append('file', file)

    return this.instance.post(url, formData, {
      ...config,
      headers: {
        'Content-Type': 'multipart/form-data',
        ...config?.headers,
      },
    })
  }

  // 下载文件
  async download(url: string, filename?: string, config?: RequestConfig): Promise<void> {
    const response = await this.instance.get(url, {
      ...config,
      responseType: 'blob',
    })

    if (process.client) {
      const blob = new Blob([response.data])
      const downloadUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = filename || 'download'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(downloadUrl)
    }
  }

  // 设置baseURL
  setBaseURL(baseURL: string) {
    this.instance.defaults.baseURL = baseURL
  }

  // 设置默认请求头
  setDefaultHeaders(headers: Record<string, string>) {
    this.instance.defaults.headers.common = {
      ...this.instance.defaults.headers.common,
      ...headers,
    }
  }

  // 设置认证token
  setAuthToken(token: string) {
    this.instance.defaults.headers.common.Authorization = `Bearer ${token}`
  }

  // 清除认证token
  clearAuthToken() {
    delete this.instance.defaults.headers.common.Authorization
  }
}

// 创建请求实例
const request = new RequestService()

// 导出请求方法
export const http = {
  get: request.get.bind(request),
  post: request.post.bind(request),
  put: request.put.bind(request),
  delete: request.delete.bind(request),
  patch: request.patch.bind(request),
  upload: request.upload.bind(request),
  download: request.download.bind(request),
  setBaseURL: request.setBaseURL.bind(request),
  setDefaultHeaders: request.setDefaultHeaders.bind(request),
  setAuthToken: request.setAuthToken.bind(request),
  clearAuthToken: request.clearAuthToken.bind(request),
}

// 导出请求实例
export default request

// 导出类型
export type { ApiResponse, RequestConfig }

